package 面试题;

import java.util.ArrayList;

public class 算法必会之数组转换 {
    public static void main(String[] args) {
        //字符串转化为数组
        String str = "aa,bbb";
        //字符串转字符串数组
        String[] strArr = str.split(",");
        //字符串转char数组
        char[] charArr = str.toCharArray();
        //读取字符串下标为i的char
        char s = str.charAt(1);

        //1.数字字符串转化为int数组
        String str2 = "123456";
        //方法一：通过charAt()可以获得对应下标的char值，用String.valueOf()转为字符串，再用Integer.parseInt()转为数字
        int[] intArr2 = new int[str2.length()];
        for (int i = 0; i < intArr2.length; i++) {
            intArr2[i] = Integer.parseInt(String.valueOf(str2.charAt(i)));
        }
        //方法二：先转为char[]在赋值给int[],效果同上，但更浪费内存
        char[] charArr2 = str2.toCharArray();
        int[] intArr3 = new int[str2.length()];
        for (int i = 0; i < intArr2.length; i++) {
            intArr3[i] = Integer.parseInt(String.valueOf(charArr2[i]));
        }

        //2.带分隔符数字字符串转化为int数组
        String str3 = "1,2,3,4,5";
        String[] strArr3 = str3.split(",");
        //分隔为字符数组后，只要循环String[]用Integer.parseInt()转为数字在赋值给int[]
        int[] intArr4 = new int[strArr3.length];
        for (int i = 0; i < strArr3.length; i++) {
            intArr4[i] = Integer.parseInt(strArr3[i]);
        }

        //3.char[]转字符串
        char[] charArr3 = new char[]{'1','2','3','4','5'};
        //用String工具类,效率最高
        String charSring1 = String.valueOf(charArr3);
        //直接new Sring
        String charSring2 = new String(charArr3);

        //4.String[]转字符串
        String[] strings = new String[]{"12","34","56","aa"};
        //用StringBuilder（效率快）或者StringBuffer（线程安全），不要用+拼接浪费内存
        StringBuilder stringBuffer1 = new StringBuilder();
        for (String string : strings) {
            stringBuffer1.append(string);
        }
        String s1 = stringBuffer1.toString();

        //5.int[]转字符串，同上
        int[] ints = new int[]{1,2,4,3};
        StringBuilder stringBuffer2 = new StringBuilder();
        for (int anInt : ints) {
            stringBuffer2.append(anInt);
        }
        String s2 = stringBuffer2.toString();
    }
}
